<template>
  <main class="main-container section-content">
    <side-menu></side-menu>
    <div class="intro-container">
      <div>
        <h3>您的基础信息</h3>
        <div class="basic-info-table">
          <div class="basic-info-cell">
            <label class="title">账户名</label>
            <label class="detail">{{ info && info.username ? info.username : '--' }}</label>
          </div>
          <div class="basic-info-cell">
            <label class="title">绑定手机</label>
            <label class="detail">{{ info && info.phoneNumber ? info.phoneNumber : '--' }}</label>
          </div>
        </div>
      </div>
      <div>
        <H3>您的安全服务</H3>
        <security-cell
          :statusIconType="hasSetPassword ? 'check-circle' : 'warning'"
          :twoToneColor="hasSetPassword ? '#52c41a' : '#faad14'"
          :statusText="hasSetPassword ? '已设置' : '未设置'"
          :securityType="'登录密码'"
          :securityDescription="'安全性高的密码可以使账号更安全。建议您定期更换密码，且设置一个包含数字和字母，并且长度在8-32之间的密码。'"
          :actionTitle="hasSetPassword ? '修改密码' : '设置密码'"
          :actionItemClick="passwordActionItemClick"
        ></security-cell>
        <security-cell
          :statusIconType="'check-circle'"
          :statusText="'已绑定'"
          :securityType="'绑定手机'"
          :securityDescription="'绑定手机后，您即可享受新材料产业服务云平台丰富的手机服务，如手机找回密码等。'"
          :actionTitle="'修改手机'"
          :actionItemClick="editPhoneNumberActionItemClick"
        ></security-cell>
      </div>
      <div>
        <a-modal v-model="editPhoneNumberVisible" :title="'修改手机号'" centered @ok="editPhoneNumberOk">
          <a-form-model ref="formForEditPhoneNumber" :model="model" :rules="validatorRulesForEditPhoneNumber">
            <a-form-model-item ref="phoneNumber" prop="phoneNumber">
              <div class="phone-number-item-container">
                <a-input
                  size="large"
                  v-model="model.phoneNumber"
                  type="text"
                  placeholder="请输入手机号"
                  @blur="
                    () => {
                      $refs.phoneNumber.onFieldBlur()
                    }
                  "
                  @change="
                    () => {
                      $refs.phoneNumber.onFieldChange()
                    }
                  "
                  @pressEnter="phoneNumberPressEnter"
                >
                  <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
                </a-input>
                <captcha-button
                  class="captcha-button-pc-sign-in"
                  ref="captchaButton"
                  :phoneNumber.sync="model.phoneNumber"
                />
              </div>
            </a-form-model-item>

            <a-row :gutter="0">
              <a-col :span="16">
                <a-form-model-item prop="captcha">
                  <a-input
                    class="text-catpcha-input"
                    v-model="model.captcha"
                    size="large"
                    type="text"
                    placeholder="请输入验证码"
                    @pressEnter="captchaPressEnter"
                  >
                    <a-icon slot="prefix" type="check-circle" :style="{ color: 'rgba(0,0,0,.25)' }" />
                  </a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-modal>
        <a-modal v-model="validatePhoneNumberVisible" :title="'需要验证您的身份'" centered @ok="validatePhoneNumberOk">
          <div class="validate-phone-number-info-container">
            <p>为确认是您本人操作，请进行身份验证。</p>
            <p>{{ phoneNumber }}</p>
          </div>

          <a-form-model ref="formForValidatePhoneNumber" :model="model" :rules="validatorRulesForValidatePhoneNumber">
            <a-form-model-item ref="captcha" prop="captcha">
              <div class="capthcha-container">
                <a-input
                  class="text-catpcha-input"
                  v-model="model.captcha"
                  size="large"
                  type="text"
                  placeholder="请输入验证码"
                  @blur="
                    () => {
                      $refs.captcha.onFieldBlur()
                    }
                  "
                  @change="
                    () => {
                      $refs.captcha.onFieldChange()
                    }
                  "
                  @pressEnter="captchaPressEnter"
                >
                  <a-icon slot="prefix" type="check-circle" :style="{ color: 'rgba(0,0,0,.25)' }" />
                </a-input>
                <captcha-button
                  class="captcha-button-pc-sign-in"
                  ref="captchaButton"
                  :phoneNumber.sync="model.phoneNumber"
                />
              </div>
            </a-form-model-item>
          </a-form-model>
        </a-modal>
        <a-modal
          v-model="editPasswordModalVisible"
          :title="hasSetPassword ? '修改密码' : '设置密码'"
          centered
          @ok="editPasswordOk"
        >
          <a-form-model ref="formForPassword" :model="model" :rules="validatorRulesForPassword">
            <a-form-model-item v-if="hasSetPassword" prop="oldPassword" :label="'原密码'">
              <a-input-password
                v-model="model.oldPassword"
                size="large"
                type="password"
                autocomplete="new-password"
                placeholder="请输入原密码"
                @pressEnter="passwordPressEnter"
              >
                <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input-password>
            </a-form-model-item>
            <a-form-model-item prop="password" :label="hasSetPassword ? '新密码' : ''">
              <a-input-password
                v-model="model.password"
                size="large"
                type="password"
                autocomplete="new-password"
                :placeholder="hasSetPassword ? '请输入新密码' : '请输入密码'"
                @pressEnter="passwordPressEnter"
              >
                <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input-password>
            </a-form-model-item>
            <a-form-model-item v-if="hasSetPassword" prop="againPassword" :label="'确认新密码'">
              <a-input-password
                v-model="model.againPassword"
                size="large"
                type="password"
                autocomplete="new-password"
                placeholder="确认新密码"
                @pressEnter="passwordPressEnter"
              >
                <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input-password>
            </a-form-model-item>
          </a-form-model>
        </a-modal>
      </div>
    </div>
  </main>
</template>

<script>
import { mapActions, mapMutations, mapState } from 'vuex'
import { md5Encode } from '@/utils/md5-util.js'
import { accountRules } from '@/utils/account-rules.js'

import SecurityCell from './components/SecurityCell.vue'
import SideMenu from './components/SideMenu.vue'

export default {
  name: 'Security',
  components: {
    SecurityCell,
    SideMenu,
  },
  props: {},

  data() {
    return {
      editPasswordModalVisible: false,
      validatePhoneNumberVisible: false,
      editPhoneNumberVisible: false,
      // editPhoneNumberVisible: true,

      model: {
        oldPassword: '',
        password: '',
        againPassword: '',
      },
    }
  },

  computed: {
    ...mapState('user', {
      info: (state) => state.info,
      oldSalt: (state) => state.oldSalt,
      salt: (state) => state.salt,
    }),
    hasSetPassword() {
      return this.info && this.info.hasSetPassword ? true : false
    },

    validatorRulesForPassword() {
      const setRules = {
        password: accountRules.passwordValidateRule,
      }
      const editRules = {
        oldPassword: accountRules.passwordValidateRule,
        password: accountRules.passwordValidateRule,
        againPassword: accountRules.passwordAgainPasswordMatchingValidateRule(this.model.password),
      }

      return this.hasSetPassword ? editRules : setRules
    },

    validatorRulesForValidatePhoneNumber() {
      return {
        captcha: [
          { required: true, message: '请输入验证码' },
          { length: 6, required: true, message: '验证码不正确' },
        ],
      }
    },
    validatorRulesForEditPhoneNumber() {
      return {
        captcha: [
          { required: true, message: '请输入验证码' },
          { length: 6, required: true, message: '验证码不正确' },
        ],
      }
    },

    phoneNumber() {
      return this.info && this.info.phoneNumber.substr(0, 3) + '****' + this.info.phoneNumber.substr(7)
    },
  },

  created() {
    this.updateUserInfo()
  },
  
  methods: {
    ...mapActions('user', [
      'getUserInfoAction',
      'resetPasswordAction',
      'validatePhoneNumberCaptchaAction',
      'editPhoneNumberAction',
      'generateSaltAction',
    ]),

    updateUserInfo() {
      const that = this
      this.getUserInfoAction()
        .then(() => {
          that.model = JSON.parse(JSON.stringify(that.info))
        })
        .catch(() => {
          that.$message.error('获取用户信息失败')
        })
    },

    passwordActionItemClick() {
      this.editPasswordModalVisible = true
    },

    editPasswordOk() {
      const that = this
      this.$refs.formForPassword.validate((valid) => {
        if (valid) {
          that
            .generateSaltAction()
            .then(() => {
              that.setOrEditPassword()
            })
            .catch((error) => {
              that.$message.error(error.message)
            })
        } else {
          that.$message.error('输入有误，请按提示修改')
        }
      })
    },

    setOrEditPassword() {
      const that = this
      const md5OldPassword = md5Encode(that.model.oldPassword, that.oldSalt)
      const md5Password = md5Encode(that.model.password, that.salt)
      const parameters = {
        edit: that.hasSetPassword,
        phoneNumber: that.model.phoneNumber,
        oldPassword: md5OldPassword,
        password: md5Password,
        salt: that.salt,
      }

      that
        .resetPasswordAction(parameters)
        .then((response) => {
          if (response && response.result && response.result.isRested) {
            if (!that.hasSetPassword) {
              that.updateUserInfo()
            }
            that.editPasswordModalVisible = false
            this.$refs.formForPassword.resetFields()
            that.$message.success(that.hasSetPassword ? '修改成功' : '设置成功')
          } else {
            that.$message.error(response.message)
          }
        })
        .catch((error) => {
          that.$message.error(error.message)
        })
    },

    passwordPressEnter() {
      this.editPasswordOk()
    },
    editPhoneNumberActionItemClick() {
      this.validatePhoneNumberVisible = true
    },
    validatePhoneNumberOk() {
      const that = this
      this.$refs.formForValidatePhoneNumber.validate((valid) => {
        if (valid) {
          const parameters = {
            phoneNumber: that.info.phoneNumber,
            captcha: that.model.captcha,
          }

          that
            .validatePhoneNumberCaptchaAction(parameters)
            .then((isValidated) => {
              if (isValidated) {
                that.updateUserInfo()
                that.validatePhoneNumberVisible = false
                that.editPhoneNumberVisible = true
                that.$refs.formForValidatePhoneNumber.resetFields()
                that.$message.success('验证成功')
              } else {
                that.$message.error('验证失败，请稍后尝试')
              }
            })
            .catch((error) => {
              that.$message.error(error.message)
            })
        } else {
          that.$message.error('输入有误，请按提示修改')
        }
      })
    },
    captchaPressEnter() {},
    editPhoneNumberOk() {
      const that = this
      this.$refs.formForEditPhoneNumber.validate((valid) => {
        if (valid) {
          const parameters = {
            phoneNumber: that.model.phoneNumber,
            captcha: that.model.captcha,
          }

          that
            .editPhoneNumberAction(parameters)
            .then((edited) => {
              if (edited) {
                that.updateUserInfo()
                that.editPhoneNumberVisible = false
                that.$refs.formForEditPhoneNumber.resetFields()
                that.$message.success('修改成功')
              } else {
                that.$message.error('修改失败')
              }
            })
            .catch((error) => {
              that.$message.error(error.message)
            })
        } else {
          that.$message.error('输入有误，请按提示修改')
        }
      })
    },
    phoneNumberPressEnter() {},
  },
}
</script>
<style scoped lang="less">
@import '~@/views/account/profile/shared.less';

.captcha-container {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.basic-info-table {
  margin: var(--margin-medium) var(--margin-medium);
}

.basic-info-cell {
  display: flex;
  flex-direction: row;
  // margin: var(--margin-x-small) var(--margin-x-small);
}
.basic-info-cell .title {
  margin: var(--margin-x-small) var(--margin-x-small);
  width: 70px;
}
.basic-info-cell .detail {
  margin: var(--margin-x-small) var(--margin-x-small);
}
.capthcha-container {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
}

.captcha-button-pc-sign-in {
  margin: var(--margin-xxx-small) var(--margin-x-small);
}
.validate-phone-number-info-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  // justify-content: center;
  padding: var(--padding-x-small) 0;
}
.phone-number-item-container {
  display: flex;
  flex-direction: row;
  align-items: center;
}

::v-deep {
  .ant-modal-body {
    padding-top: var(--padding-x-small) !important;
  }
}
</style>

